package com.zhucai.credit.service.impl.transactional;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhucai.credit.bean.CreditRecord;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.model.CreditInvoiceEntity;
import com.zhucai.credit.repository.CashierOrderItemRepository;
import com.zhucai.credit.repository.CreditInvoiceRepository;
import com.zhucai.credit.repository.PaymentOrderRepository;
import com.zhucai.credit.repository.PaymentPlanRepository;

@Service
public class InvoiceUtilServiceImpl {
	@Autowired
	private CreditInvoiceRepository creditInvoiceRepository;
	@Autowired
	private CashierOrderItemRepository cashierOrderItemRepository;
	@Autowired
	private PaymentOrderRepository paymentOrderRepository;
	@Autowired
	private PaymentPlanRepository paymentPlanRepository;

	/**
	 * 操作发票
	 */
	public CreditInvoiceEntity operationInvoice(CreditRecord cr) {
		CreditInvoiceEntity cie = operInvoice(cr);
		Integer coo = paymentPlanRepository.updateInvoiceFileId(cie.getTid(),cr.getPaymentId());
		if(coo != 1){
			throw new RuntimeException("更新计划付款发票id异常！");
		}
		return cie;
	}
	private CreditInvoiceEntity operInvoice(CreditRecord cr){
		CreditInvoiceEntity creditInvoiceEntity = new CreditInvoiceEntity();
		if(cr.getInvoiceTid() != null && cr.getInvoiceTid() != 0){
			creditInvoiceEntity = creditInvoiceRepository.findByTidAndStatusNot(cr.getInvoiceTid(), HelpConstant.Status.delete);
			creditInvoiceRepository.updateInvoice(cr.getInvoiceAmount(), cr.getInvoiceCode().trim(), cr.getInvoiceDate(), cr.getInvoiceNo().trim(), cr.getInvoiceFileId(), cr.getInvoiceTid(), cr.getUserId(), cr.getInvoiceFileName());
			creditInvoiceEntity = creditInvoiceRepository.findByTidAndStatusNot(cr.getInvoiceTid(), HelpConstant.Status.delete);
		}else{
			creditInvoiceEntity.setCreateUser(cr.getUserId());
			creditInvoiceEntity.setCreTime(new Date());
			creditInvoiceEntity.setInvoiceCode(cr.getInvoiceCode().trim());
			creditInvoiceEntity.setInvoiceDate(cr.getInvoiceDate());
			creditInvoiceEntity.setInvoiceAmount(cr.getInvoiceAmount());
			creditInvoiceEntity.setInvoiceFileId(cr.getInvoiceFileId());
			creditInvoiceEntity.setInvoiceNo(cr.getInvoiceNo().trim());
			creditInvoiceEntity.setInvoiceFileName(cr.getInvoiceFileName());
			creditInvoiceEntity.setCheckTrueStatus(0);
			creditInvoiceRepository.saveAndFlush(creditInvoiceEntity);
		}
		
		return creditInvoiceEntity;
	}
	/**
	 * 判断当前用户输入信息和发票验真结果是否一致
	 */
	public Boolean checkResultTrue(CreditInvoiceEntity ci){
		try {
			if(ci != null && ci.getInvoiceAmount().compareTo(ci.getCheckInvoiceAmount())==0 && ci.getInvoiceCode().equals(ci.getCheckInvoiceCode()) &&
					ci.getInvoiceDate().compareTo(ci.getCheckInvoiceDate()) == 0 && ci.getInvoiceNo().equals(ci.getCheckInvoiceNo())){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
}
